package com.csii.activiti.server.core.utils;

import com.csii.activiti.server.core.constant.CommonConstant;
import com.csii.activiti.server.core.entity.ActFlowCondition;
import com.csii.activiti.server.core.entity.ActFlowConditionGroup;

import java.util.List;

public class ConversionELExperssionUtils {
    private static final String SUBSTITUTION = "=";
    private static final String DOUBLE_SUBSTITUTION = "==";


    public static String conversionFlowConditionToEL(List<ActFlowCondition> conditions){
        if (conditions == null || conditions.isEmpty()){
            return null;
        }
        StringBuilder sb = new StringBuilder();
        sb.append("${");
        boolean isFirst = true;
        for (ActFlowCondition condition : conditions) {
            if (isFirst){
                isFirst = false;
            }else{
                sb.append("&&");
            }
            String operation = condition.getOperation();
            if (SUBSTITUTION.equals(operation)){
                operation = DOUBLE_SUBSTITUTION;
            }
            sb.append(CommonConstant.FORM_DATA).append(".").append(condition.getFormElementKey()).append(operation).append("'").append(condition.getValue()).append("'");
        }
        sb.append("}");
        return sb.toString();
    }

    public static String conversionFlowConditionGroupToEL(List<ActFlowConditionGroup> conditionGroups){
        if (conditionGroups == null || conditionGroups.isEmpty()){
            return null;
        }
        StringBuilder sb = new StringBuilder();
        sb.append("${(");
        boolean isConditionGroupFirst = true;
        for (ActFlowConditionGroup conditionGroup : conditionGroups) {

            if (isConditionGroupFirst){
                isConditionGroupFirst = false;
            }else {
                sb.append("||(");
            }

            boolean isConditionFirst = true;
            for (ActFlowCondition condition : conditionGroup.getConditions()) {
                if (isConditionFirst){
                    isConditionFirst = false;
                }else{
                    sb.append("&&");
                }
                String operation = condition.getOperation();
                if (SUBSTITUTION.equals(operation)){
                    operation = DOUBLE_SUBSTITUTION;
                }
                sb.append(CommonConstant.FORM_DATA).append(".").append(condition.getFormElementKey()).append(operation).append("'").append(condition.getValue()).append("'");
            }
            sb.append(")");
        }
        sb.append("}");
        return sb.toString();
    }
}
